package com.gaff.emp.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientResponseException;

import java.sql.SQLDataException;
import java.sql.SQLException;


@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());


    @ExceptionHandler(IllegalArgumentException.class)
    public R handleIllegalArgumentException(Exception e) {
        logger.error("handleIllegalArgumentException", e);
        return R.error(400, "请求参数异常：" + e.getMessage());
    }

    @ExceptionHandler(EmpException.class)
    public R handleEmpException(EmpException e) {
        logger.error("handleEmpException", e);
        return R.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(DataAccessException.class)
    public R handleDataAccessException(DataAccessException e) {
        logger.error("handleDataAccessException", e);
        return R.error("数据访问错误");
    }

    @ExceptionHandler(SQLException.class)
    public R handleSqlException(SQLException e) {
        logger.error("handleSqlException", e);
        return R.error("数据库操作错误");
    }

    @ExceptionHandler(SQLDataException.class)
    public R handleSqlDataException(SQLDataException e) {
        logger.error("handleSqlDataException", e);
        return R.error("数据库操作错误");
    }

    @ExceptionHandler(RestClientResponseException.class)
    public R handleRestClientResponseException(RestClientResponseException e) {
        logger.error("handleRestClientResponseException", e);
        int status = e.getRawStatusCode();
        String msg = e.getResponseBodyAsString();
        return R.error(status, msg);
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        logger.error("handleException", e);
        return R.error(e.getMessage());
    }
}
